﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WAD.WEB.AppCode;
using WAD.Model;
using WAD.DAL;
using System.Data.SqlClient;

namespace WAD.WEB.Client.Ajax
{
    /// <summary>
    /// 收藏 的摘要说明
    /// </summary>
    public class Collect : AjaxBase
    {
        public override void AjaxMethodDispatch(String identity)
        {
            switch (identity)
            {
                case "add": this.Add(); break;
                case "remove": this.Remove(); break;
                case "getlist": this.GetList(); break;
            }
        }
        /// <summary>
        /// 添加收藏
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void Add()
        {
            IsLogin();

            int type = Parse.Int("type", 0);//文章id
            int articleId = Parse.Int("article_id", 0);//文章id
            String url = HttpUtility.UrlDecode(Parse.String("url"));//文章id

            //验证
            if (type == 0 || (articleId ==0 && String.IsNullOrEmpty(url)))
            {
                ParamError();
            }

            MCollect m = new MCollect() { article_id = articleId, user_id = UserId, type = type, url = url };

            try
            {
                bool flag = DaoCollect.Add(m);
                if (flag)
                {
                    Success();
                }
                else
                {
                    Fail();
                }
            }
            catch (SqlException e)
            {
                if (e.Message.IndexOf("UNIQUE KEY") != -1)
                {
                    JsonResult(Message.Code.IS_COLLECT, Message.Msg.IS_COLLECT);
                }
                else
                {
                    throw e;
                }
            }
        }



        /// <summary>
        /// 移除收藏
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void Remove()
        {
            IsLogin();
            int id = Parse.Int("id", 0);

            if (id == 0)
            {
                ParamError();
            }

            if (DaoCollect.Delete(id, UserId))
            {
                Success();
            }
            else
            {
                Fail();
            }

        }


        /// <summary>
        /// 获取收藏列表
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void GetList()
        {
            int pageIndex = Parse.Int("page_index", 1);//当前页

            PageData pg = DaoCollect.GetList(pageIndex, 20, UserId);

            if (pg.itemCount == 0)
            {
                DataEmpty();
            }
            else
            {
                Success(pg);
            }
        }
    }
}